package com.wx.house.terminal.api.Interceptor;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wx.house.common.util.RedisUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.util.StringUtil;
import com.wx.house.common.base.BaseController;
import com.wx.house.common.base.Constant;
import com.wx.house.common.exception.UserException;
import com.wx.house.common.util.JwtUtils;
import io.jsonwebtoken.Claims;


public class LoginInterceptor extends BaseController implements HandlerInterceptor {
	@Resource
	private RedisUtil redisUtil;

	private static String TENANT_TERMINAL_SIGN = "WX:HOUSING:TERMINAL_SIGN:%s";
/***
 * 进入
 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws Exception {
		//step1.获取用户访问的url
		String requestURL = request.getRequestURL().toString();
		//去掉path参数，获取真正api
		if (!requestURL.endsWith("/")) {
		//  /accountcenter/department  =>   /accountcenter/
		requestURL = requestURL.replace(requestURL.split("/")[requestURL.split("/").length - 1], "");
		}
		//需要token校验的url
		List<String> a=new ArrayList<>();
		a.add("/common/idCard/");//实名认证
		a.add("/tenant/v1.0.0/");
//		a.add("/tenant/v1.0.0/contract");//用户合同列表
//		a.add("/tenant/v1.0.0/contract/detail");//用户合同详情
//		a.add("/tenant/v1.0.0/user");//用户实名信息
//		a.add("/tenant/v1.0.0/user/idCard/");//用户提交实名认证请求
//		a.add("/tenant/v1.0.0/order");//用户申请创建订单
//		a.add("/tenant/v1.0.0/order/detail/{id}");//缴费订单详情
//		a.add("/tenant/v1.0.0/order/selectallordermap/");//查询所有的订单
//		a.add("/tenant/v1.0.0/order/{id}");//取消订单
//		a.add("/tenant/v1.0.0/index");//app首页
//		a.add("/tenant/v1.0.0/index/expense");//缴费记录明细
//		a.add("/tenant/v1.0.0/index/indexPayFees/");//app首页-待缴收费
//		a.add("/tenant/v1.0.0/index/pendingPayment/");//订单管理-缴费订单[如果往期没交,会有多条数据]
//		a.add("/tenant/sign/logout");//退出登陆
//		a.add("/tenant/sign/resetPassword");//重置密码-初次设置密码
//		a.add("/tenant/sign/signIn");//登陆
//		a.add("/common/idCard/");//短信验证码
		if(!a.stream().anyMatch(requestURL::contains)) {
			return HandlerInterceptor.super.preHandle(request, response, handler);
		}
		else {
			//step2.获取用户token
			String token = request.getHeader("authorization");
			Claims claims;
			try {
				claims = JwtUtils.builder().token(token).build().claims();
			} catch (Exception e) {
				e.printStackTrace();
				response.setStatus(603);
				throw new UserException("登录信息错误",603);
			}
			//解析用户token
			String phone = claims.get("phone").toString();
			String redisToken =redisUtil.get(String.format(TENANT_TERMINAL_SIGN, phone));
			if(StringUtil.isEmpty(redisToken)) {
				response.setStatus(601);
				throw new UserException("您的登录已过期",601);
			}
			//判断token是否一致，如果不一致提示：您已经被迫下线
			if(!token.equals(redisToken)) {
				response.setStatus(602);
				throw new UserException("您已被迫下线",602);
			}
			return HandlerInterceptor.super.preHandle(request, response, handler);
		}
}

/***
 * 调用完成后
 */
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                       ModelAndView modelAndView) throws Exception {
//		System.out.println("拦截器-postHandle:controller方法之后,视图渲染之前...");
//		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}

/***
 * 完成之后，用于资源清理
 */
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
		throws Exception {
//		System.out.println("拦截器-视图渲染后:资源清理...");
//		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
	
}
